package com.yzc.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzc.execption.ZcException;
import com.yzc.mapper.TicketMainOrderMapper;
import com.yzc.model.entity.ticket_order.OrderMain;
import com.yzc.result.ResultCodeEnum;
import com.yzc.service.TicketMainOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.yzc.rabbit.OrderStatus.status_CANCELED;

@Service
public class TicketMainOrderServiceImpl extends ServiceImpl<TicketMainOrderMapper, OrderMain>
        implements TicketMainOrderService {

    @Autowired
    private TicketMainOrderMapper mapper;

    @Override
    public Page<OrderMain> listOrders(Page<OrderMain> page, Long userId) {
        LambdaQueryWrapper<OrderMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderMain::getUserId, userId)
                .orderByDesc(OrderMain::getCreateTime);
        return mapper.selectPage(page, queryWrapper);
    }

    @Override
    public OrderMain getOrderDetail(Long orderId) {
        LambdaQueryWrapper<OrderMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderMain::getOrderId, orderId);
        return mapper.selectOne(queryWrapper);
    }

    @Override
    public void cancelOrder(Long orderId, Long userId, String cancelReason) {
        LambdaUpdateWrapper<OrderMain> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(OrderMain::getOrderId, orderId)
                .eq(OrderMain::getUserId, userId)
                .set(OrderMain::getCancelReason, cancelReason)
                .set(OrderMain::getOrderStatus, status_CANCELED);
        int update = mapper.update(null, updateWrapper);
        if (update == 0) {
            throw new ZcException(ResultCodeEnum.FAIL.getCode(), "订单不存在或状态不允许取消");
        }
    }
}
